package android.tusnotas.core;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.tusnotas.beans.Course;
import android.tusnotas.beans.ListaNotificaciones;
import android.tusnotas.beans.PushNotification;
import android.tusnotas.changes.PushChange;
import android.tusnotas.connector.webservice.WebServiceCaller;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.model.TusNotasModel;
import android.tusnotas.notification.NewPushNotification;
import android.tusnotas.notification.TusNotasNotification;
import android.tusnotas.parser.push.PushNotificationParser;
import android.tusnotas.util.Devel;
import android.util.Log;

public class PushAnalyser {
	private WebServiceCaller caller = new WebServiceCaller();

	private int ttt = 5;//times to try before giving up connection try

	public ListaNotificaciones doGetPushNotifications(String appId, String androidId) throws RemoteReadingException, ProcessingInstancesException{
		String XML = doGetPushNotification(appId, androidId);

		ListaNotificaciones n = doObtainPushNotification(XML);
		
		return n;
	}

	private ListaNotificaciones doObtainPushNotification(String XML) throws ProcessingInstancesException{
		ListaNotificaciones n = null;

		PushNotificationParser notificationParser = new PushNotificationParser();
		try {
			n = notificationParser.parseXML(XML);
		} catch (Exception e) {
			e.printStackTrace();
			Log.w(getClass().getName(),"Can't read push notification");
		}
		return n;
	}

	private String doGetPushNotification(String appId, String androidId) throws RemoteReadingException{
		String XML="";
		try {
			caller.setPushNotification(appId, androidId);
			XML = persistentCaller();
		} catch (Exception e) {
			if( Devel.fullDevel){
				Log.w(this.getClass().getName(), "No notifications were found");
			}
			RemoteReadingException rwce = new RemoteReadingException();
			rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
			throw rwce;
		}
		return XML;
	}

	private String persistentCaller() throws RemoteReadingException{	
		while( ttt > 0){
			try{
				String XML = caller.execute();
				return XML;
			}catch(RemoteReadingException e){}
			ttt--;
		}
		throw new RemoteReadingException();
	}

	public List<TusNotasNotification> getBarNotifications(ListaNotificaciones lista, Context context){

		TusNotasModel tnm = TusNotasModel.getTusNotasModel(context);

		List<TusNotasNotification> result = new ArrayList<TusNotasNotification>();

		for(int i=0; i<lista.getNotifications().size(); i++){
			PushNotification n = lista.getNotifications().get(i);
			Course c = tnm.selectCourseByIdAula(new Integer(n.getIdAula()));
			TusNotasNotification notification = new NewPushNotification(new PushChange(context,n,c));
			result.add(notification);
		}
		return result;
	}
}
